import { useUserStoreWithOut } from '@/store/modules/user'

export default {
  install(Vue, { router }) {
    const userStore = useUserStoreWithOut()
    let currentPage = ''
    let traceId = ''

    router.beforeEach((to, from, next) => {
      traceId = sessionStorage.getItem('traceId') || ''
      currentPage =
        sessionStorage.getItem('currentPage') || ''
      if (traceId) {
        userStore.updateTrackingPoint({
          traceId,
          exitFlag: 1
        })
      }
      next()
    })

    router.afterEach((to, from) => {
      traceId = Date.now().toString()
      currentPage = to.path
      sessionStorage.setItem('traceId', traceId)
      sessionStorage.setItem('currentPage', currentPage)
      userStore.createTrackingPoint({
        traceId,
        resourcePath: from.path,
        path: currentPage,
        terminalType: 1
      })
    })

    document.addEventListener('visibilitychange', () => {
      traceId = sessionStorage.getItem('traceId') || ''
      currentPage =
        sessionStorage.getItem('currentPage') || ''
      if (traceId) {
        userStore.updateTrackingPoint({ traceId })
      }
    })
  }
}
